import Koa from 'koa'
import koaStatic from 'koa-static'
import fs from 'fs'
import Download from './utils/download'
import packaging from './utils/packaging'

const imageList = [
    'http://placekitten.com/g/100/100',
    'http://placekitten.com/g/200/150',
    'http://placekitten.com/g/300/200'
]

const app = new Koa()
const indexHtml= fs.readFileSync('index.html')

// 静态资源配置
app.use(koaStatic('./zip'))
app.use(async ctx => {
    const { request: req } = ctx

    // 下载 API
    if (req.path === '/download' && req.method === 'GET') {
        const download = new Download(imageList)

        try {
            console.log('download start')
            const list = await download.start()
            console.log('download end')

            console.log('packaging start')
            const path = await packaging(list)
            console.log('packaging end')

            ctx.body = {
                path
            }
        } catch (e) {
            ctx.body = e
        }
    } else {
        ctx.type = 'text/html'
        ctx.body = indexHtml
    }
})

const port = 3000
app.listen(port)

console.log(`http://localhost:${port}`)
